package com.hykj.xxltest.utils;

import com.alibaba.fastjson.JSON;
import com.hykj.xxltest.config.AlipayConfig;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

public class AlipayUtil {

    private static Logger logger = Logger.getLogger(AlipayUtil.class);

    /**
     * 开发文档
     * app支付
     * https://docs.open.alipay.com/204/105465/
     * @param code
     * @param money 分 amount 元
     * @return
     * @throws Exception
     */
    public static String alipay(String code, BigDecimal money)  {



        Map<String, String> biz_content = new HashMap<>();
        biz_content.put("body", "全保网");
        biz_content.put("subject", "全保网");
        biz_content.put("out_trade_no", code);
        biz_content.put("total_amount", money.toString());
        biz_content.put("product_code", "QUICK_MSECURITY_PAY");
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String timestamp = sdf.format(date);

        Map<String, String> aliPayMap = new HashMap<>();
        aliPayMap.put("app_id", AlipayConfig.appid);
        aliPayMap.put("method", "alipay.trade.app.pay");
        aliPayMap.put("charset", "utf-8");
        aliPayMap.put("sign_type", "RSA2");
        aliPayMap.put("notify_url", "http://www.yishen.mobi:8081/aliPayNotify");
        aliPayMap.put("timestamp", timestamp);
        aliPayMap.put("version", "1.0");
        aliPayMap.put("biz_content", JSON.toJSONString(biz_content));
        String content = AlipaySignature.getSignContent(aliPayMap);

        String sign = null;
        try {
            sign = AlipaySignature.rsaSign(content, AlipayConfig.private_key, "utf-8", "RSA2");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        aliPayMap.put("sign", sign);
        logger.info("生成支付宝支付 请求参数 "+JSON.toJSONString(aliPayMap));
        StringBuffer content2 = new StringBuffer();
        ArrayList keys = new ArrayList(aliPayMap.keySet());
        Collections.sort(keys);
        int index = 0;

        for(int i = 0; i < keys.size(); ++i) {
            String key = (String)keys.get(i);
            String value = (String)aliPayMap.get(key);
            if(StringUtils.isNotEmpty(key)&&StringUtils.isNotEmpty(value)) {
                try {
                    content2.append((index == 0?"":"&") + key + "=" + URLEncoder.encode(value,"UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                ++index;
            }
        }

        logger.info("r  "+content2.toString());
        return content2.toString();
    }

}
